package com.kay.classloader;

import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Description:自定义类加载器
 * @Author: Kay
 * @CreateDate: 2021/8/4$ 13:16$
 * @UpdateUser: Kay
 * @UpdateDate: 2021/8/4$ 13:16$
 */
public class WebClassloader extends ClassLoader {
    private String classpath;

    public WebClassloader(String classpath) {
        this.classpath = classpath;
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        return super.loadClass(name);
    }

    /**
     * 根据创建WebClassloader时传入的 classpath 路径下，加载相应的class文件
     * @param name
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] data = new byte[0];
        try {
            data = loadByte(name);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // defineClass 将字节数组转为class对象
        return defineClass(name, data, 0, data.length);
    }

    private byte[] loadByte(String name) throws IOException {
        name = name.replaceAll("\\.", "/");
        System.out.println("==================>>>>>>>>>>>>>> absolute className : " + classpath + "/" + name + ".class");
        FileInputStream fileInputStream = new FileInputStream(classpath + "/" + name + ".class");
        int available = fileInputStream.available();
        byte[] data = new byte[available];
        fileInputStream.read(data);
        fileInputStream.close();
        return data;
    }
}
